from flask import Flask, jsonify, request, session, abort
from functools import wraps
import argparse
import pymongo
import string
import os

from werkzeug.utils import redirect

myclient = pymongo.MongoClient(
    "mongodb://apps_web_demo:apps_web_demo@115.29.150.66:27017/web_demo")
db = myclient["web_demo"]

app = Flask("apps_zjh_web_login_demo", static_url_path="/static",
            static_folder="app_demo/main/static")

app.config["SECRET_KEY"] = "123"

# 登录


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return """<form action="/login" method="post"><input name="username"><input name="password"><button>登录</button></form>"""
    else:
        if request.form["username"] == "admin" and request.form["password"] == "admin":
            session["username"] = "admin"
            return redirect("/chess")
        return redirect("/login")


def verify_before_request(controller):
    @wraps(controller)
    def decorated(*args, **kwargs):
        username = session.get("username")
        if username and username == "admin":
            return controller(*args, **kwargs)
        else:
            return abort(403)

    return decorated


# 前端框架


@app.route("/chess")
@verify_before_request
def page():
    """
    前端框架数据接口
    """
    data = db.get_collection("chess").find_one()
    return """
    <!DOCTYPE html>
    <html lang="en">

    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="/static/vue.js"></script>
    </head>

    <body>
      <div id="app">
      <iframe v-if="chess_show" src="http://www.zgxqds.com/loadQP.htm" :name="`<br>[DhtmlXQ_binit]${chess_data.binit}[/DhtmlXQ_binit]<br>[DhtmlXQ_title]${chess_data.title}[/DhtmlXQ_title]<br>[DhtmlXQ_red]${chess_data.red}[/DhtmlXQ_red]<br>[DhtmlXQ_black]${chess_data.black}[/DhtmlXQ_black]<br>[DhtmlXQ_result]${chess_data.result}[/DhtmlXQ_result]<br>[DhtmlXQ_date]${chess_data.date}[/DhtmlXQ_date]<br>[DhtmlXQ_place]${chess_data.place}[/DhtmlXQ_place]<br>[DhtmlXQ_event]${chess_data.event}[/DhtmlXQ_event]<br>[DhtmlXQ_open]${chess_data.open}[/DhtmlXQ_open]<br>[DhtmlXQ_movelist]${chess_data.move_list}[/DhtmlXQ_movelist]<br>`" frameborder="0" scrolling="no" height="378" width="535"></iframe>
      </div>
    </body>
    <script>
        const { ref, reactive, computed, onUnmounted } = Vue;
      const App = {
        components: {
        },
        setup(props) {
          const chess_data = reactive({
            "binit": "",
            "title": "",
            "red": "",
            "black": "",
            "result": "",
            "place": "",
            "event": "",
            "open": "",
            "date": "",
            "move_list": "",
          });
          const chess_show = ref(false);
          let xhr = new XMLHttpRequest();
          xhr.open("get", "/data");
          xhr.onload = (res)=>{
            for(let key in chess_data) {
              chess_data[key] = JSON.parse(res.target.response)[key];
            }
            chess_show.value = true;
          };
          xhr.send(null);
          return {
            chess_data,
            chess_show
          }
        }
      };
      app = Vue.createApp(App);
      app.mount('#app');
    </script>

    </html>
    """


@app.route("/data")
@verify_before_request
def data():
    """
    前端框架页面接口
    """
    data = db.get_collection("chess").find_one()
    return jsonify({
        "binit": data["binit"],
        "title": data["title"],
        "red": data["red"],
        "black": data["black"],
        "result": data["result"],
        "place": data["place"],
        "event": data["event"],
        "open": data["open"],
        "date": data["date"],
        "move_list": data["move_list"]
    })

# 模版引擎 推荐jinja


@app.route("/chess_t")
@verify_before_request
def chess():
    data = db.get_collection("chess").find_one()
    html_template = string.Template(
        """<iframe src="http://www.zgxqds.com/loadQP.htm" name="<br>[DhtmlXQ_binit]$binit[/DhtmlXQ_binit]<br>[DhtmlXQ_title]$title[/DhtmlXQ_title]<br>[DhtmlXQ_red]$red[/DhtmlXQ_red]<br>[DhtmlXQ_black]$black[/DhtmlXQ_black]<br>[DhtmlXQ_result]$result[/DhtmlXQ_result]<br>[DhtmlXQ_date]$date[/DhtmlXQ_date]<br>[DhtmlXQ_place]$place[/DhtmlXQ_place]<br>[DhtmlXQ_event]$event[/DhtmlXQ_event]<br>[DhtmlXQ_open]$open[/DhtmlXQ_open]<br>[DhtmlXQ_movelist]$move_list[/DhtmlXQ_movelist]<br>" frameborder="0" scrolling="no" height="378" width="535"></iframe>""")

    return html_template.substitute({
        "binit": data["binit"],
        "title": data["title"],
        "red": data["red"],
        "black": data["black"],
        "result": data["result"],
        "place": data["place"],
        "event": data["event"],
        "open": data["open"],
        "date": data["date"],
        "move_list": data["move_list"]
    })


def main(debug=False):
    parser = argparse.ArgumentParser(
        description='APPS Flask Web Demo.'
    )
    parser.add_argument('-l', '--host', default="")
    parser.add_argument('-p', '--port', default=-1)

    args = parser.parse_args()
    host = args.host
    port = int(args.port)
    app.run(host=host if host else None,
            port=port if port != -1 else None, debug=debug)


if __name__ == "__main__":
    main(True)
